package org.fdy.common.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.fdy.common.core.units.LoginUtils;

import java.time.LocalDateTime;

/**
 * <p>说明： </P>
 *
 * @author: fangdayang
 * @create: 2023-10-21 17:32
 **/
@Slf4j
public class CommonMetaObjectHandler implements MetaObjectHandler {
    /**
     * 创建人
     */
    private static final String CREATE_UID = "createId";

    /**
     * 更新人
     */
    private static final String UPDATE_UID = "updateId";

    /**
     * 创建时间
     */
    private static final String CREATE_TIME = "createTime";

    /**
     * 修改时间
     */
    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        Long uid = currentUid();
        strictInsertFill(metaObject, CREATE_UID, Long.class, uid);
        strictInsertFill(metaObject, UPDATE_UID, Long.class, uid);
        strictInsertFill(metaObject, CREATE_TIME, LocalDateTime.class, LocalDateTime.now());
        strictInsertFill(metaObject, UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        strictUpdateFill(metaObject, UPDATE_UID, Long.class, currentUid());
        strictUpdateFill(metaObject, UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
    }

    public Long currentUid() {
        try {
            return LoginUtils.getUserId();
        } catch (Exception ignore) {
            log.error("获取用户id失败");
        }
        return 1L;
    }
}
